package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.CategoryRepository;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryService implements ICategoryService {
    @Autowired
    public CategoryRepository catgoryRepository;
    @Autowired
    public DrinkRepository drinkRepository;

    @Override
    public List<Category> gatALLCategory() {
        return catgoryRepository.findAll();
    }

    @Override
    public Category selectbyID(Integer id) {
        return catgoryRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delcategoryByid(Integer id) {
        //将Drink中关联该id的  category置为空
        //查询到关联id的drink
        List<Drink> drinks = drinkRepository.findDrinkByCategory_Id(id);
        //更新drinks
        for (Drink drink : drinks) {
            drink.setCategory(null);
            drinkRepository.save(drink);
        }
        //删除指定分类
        catgoryRepository.deleteById(id);
    }

    @Override
    public void setCategory(Category category) {
        catgoryRepository.save(category);
    }

    @Override
    public void addNewCategory(Category category) {
        catgoryRepository.save(category);
    }

}
